"ui";
const storage = storages.create("Seckill");

const isShow = storage.get("show", false);
const sleepTime = storage.get("sleepTime", 1100);
const itemNum = storage.get("itemNum", 2);
const itemIndex = storage.get("itemIndex", 0);
const xAxis = storage.get("xAxis", 969);
const yAxis = storage.get("yAxis", 1344);

ui.statusBarColor("#1495E7");
ui.layout(
    <frame>
        <vertical>
            <appbar>
                <toolbar id="toolbar" bg="#1495E7" title="多点助手"></toolbar>
            </appbar>
            <ScrollView>
                <vertical>
                    <card
                        w="*"
                        h="70"
                        margin="10 5"
                        cardCornerRadius="2dp"
                        cardElevation="1dp"
                        foreground="?selectableItemBackground"
                    >
                        <horizontal gravity="center_vertical">
                            <View bg="#1495E7" h="*" w="5" />
                            <vertical padding="10 8" h="auto" w="0" layout_weight="1">
                                <horizontal>
                                    <Switch
                                        id="autoService"
                                        text="无障碍服务"
                                        checked="{{auto.service != null}}"
                                        padding="8 8 8 8"
                                        textSize="14"
                                    />
                                    <Switch
                                        id="isShow"
                                        text="悬浮窗"
                                        checked="{{isShow}}"
                                        padding="8 8 8 8"
                                        textSize="14"
                                    />
                                </horizontal>
                            </vertical>
                        </horizontal>
                    </card>
                    <card
                        w="*"
                        h="270"
                        margin="10 5"
                        cardCornerRadius="2dp"
                        cardElevation="1dp"
                        foreground="?selectableItemBackground"
                    >
                        <horizontal gravity="center_vertical">
                            <View bg="#1495E7" h="*" w="5" />
                            <vertical padding="10 8" h="auto" w="0" layout_weight="1">
                                <horizontal>
                                    <text text="跳转时间" />
                                    <input
                                        w="*"
                                        id="sleepTime"
                                        inputType="number"
                                        text="{{sleepTime}}"
                                    />
                                </horizontal>
                                <horizontal>
                                    <text text="商品数量" />
                                    <input
                                        w="*"
                                        id="itemNum"
                                        inputType="number"
                                        text="{{itemNum}}"
                                    />
                                </horizontal>
                                <horizontal>
                                    <text text="商品坐标" />
                                    <input
                                        w="*"
                                        id="itemIndex"
                                        inputType="number"
                                        text="{{itemIndex}}"
                                    />
                                </horizontal>
                                <horizontal>
                                    <text text="X坐标" />
                                    <input
                                        w="*"
                                        id="xAxis"
                                        inputType="number"
                                        text="{{xAxis}}"
                                    />
                                </horizontal>
                                <horizontal>
                                    <text text="Y坐标" />
                                    <input
                                        w="*"
                                        id="yAxis"
                                        inputType="number"
                                        text="{{yAxis}}"
                                    />
                                </horizontal>
                            </vertical>
                        </horizontal>
                    </card>
                    <vertical padding="5 5">
                        <button
                            marginTop="10"
                            id="start"
                            h="80"
                            style="Widget.AppCompat.Button.Colored"
                            text="启动"
                            textSize="20"
                        />
                        <button
                            marginTop="10"
                            id="close"
                            h="60"
                            style="Widget.AppCompat.Button.Colored"
                            text="关闭"
                            textSize="20"
                        />
                        <button
                            marginTop="10"
                            id="save"
                            h="60"
                            style="Widget.AppCompat.Button.Colored"
                            text="保存配置"
                            textSize="20"
                        />
                        <button
                            marginTop="10"
                            id="exit"
                            h="60"
                            style="Widget.AppCompat.Button.Colored"
                            text="退出"
                            textSize="20"
                        />
                    </vertical>
                </vertical>
            </ScrollView>
        </vertical>
    </frame>
);

var mainThread;
ui.start.on("click", function () {
    if (auto.service == null) {
        toast("请先开启无障碍服务！");
        return;
    }
    mainThread = threads.start(function () {
        run();
    });
});

// 关闭按钮
ui.close.on("click", function () {
    console.log('关闭按钮点击');
    if (mainThread) {
        console.log('主子线程存在', mainThread);
        // 关闭所有子线程
        threads.shutDownAll();
        // 清空日志框
        console.clear();
        // 隐藏日志框
        console.hide();
    }
});

// 保存配置
ui.save.on("click", function () {
    var diff_time = ui.sleepTime.text();
    var item_num = ui.itemNum.text();
    var item_index = ui.itemIndex.text();
    var xAxis = ui.xAxis.text();
    var yAxis = ui.yAxis.text();
    storage.put("sleepTime", diff_time);
    storage.put("itemNum", item_num);
    storage.put("itemIndex", item_index);
    storage.put("xAxis", xAxis);
    storage.put("yAxis", yAxis);
});

ui.autoService.on("check", function (checked) {
    // 用户勾选无障碍服务选项时，跳转到页面让用户去开启
    if (checked && auto.service == null) {
        app.startActivity({
            action: "android.settings.ACCESSIBILITY_SETTINGS"
        });
    }
    if (!checked && auto.service != null) {
        auto.service.disableSelf();
    }
});

// 当用户回到本界面时，resume事件会被触发
ui.emitter.on("resume", function () {
    // 此时根据无障碍服务的开启情况，同步开关状态
    ui.autoService.checked == auto.service != null;
})

ui.isShow.on("check", function (checked) {
    app.startActivity({
        action: "android.settings.action.MANAGE_OVERLAY_PERMISSION"
    });
});

// 退出脚本
ui.exit.on("click", function () {
    exit();
});

function run() {
    var appName = "多点";
    launchApp(appName);
    console.show();
    // 第一次获取时间差
    var diff_duodian_time = getDuoDianTime();
    sleep_now_time = parseInt(storage.get("sleepTime", 1000));
    // 获取下一个目标时间
    var seck_time = getNextSeckillTime();
    console.log(new Date(seck_time));

    // 时间判断是否可以开始抢购（调试时输出倒计时）
    while (true) {
        // 当前时间转多点时间毫秒数
        var curr_datetime = new Date().getTime() + diff_duodian_time;
        //console.log('本地时间转多点时间：', formatDate(new Date(curr_datetime)));
        // 多点时间加上跳转时间大于等于目标时间则退出时间轮询
        if (curr_datetime + sleep_now_time >= seck_time) {
            break;
        }
        // 目标时间前10秒外每3秒轮询获取时间差
        new_diff_time = getSleepTime(seck_time);
        if (new_diff_time != -999) {
            // 赋值新时间差
            diff_duodian_time = new_diff_time;
        }
        //sleep(10);
        // var itemIndex = storage.get("itemIndex", 0)
        // console.log("商品坐标", itemIndex);
    }

    doSeckill();
}

// 在9点59分50秒前每3秒获取最新延迟
function getSleepTime(seck_time) {
    if (seck_time - new Date().getTime() > 10000) {
        var diff_duodian_time = getDuoDianTime();
        var now_time = new Date();
        now_time = new Date(now_time.getTime() + diff_duodian_time);
        console.log('本地时间转多点时间：', formatDate(now_time));
        sleep(3000);
        return diff_duodian_time;
    }
    return -999
}

// 执行抢购逻辑
function doSeckill() {
    // 启动线程
    threads.start(function () {
        // 时间相关
        loop1();
    });
}


// 循环1查找立即抢购按钮
function loop1() {
    console.log('执行立即抢购');
    while (true) {
        var itemIndex = storage.get("itemIndex", 0)
        var do1 = className("android.widget.Button").text('立即抢购').findOnce(itemIndex);
        if (do1) {
            console.log('点击【立即抢购】');
            do1.click();
            threads.start(function () {
                loop2();
            });
            break;
        }
    }
}


// 循环2查找预约抢购按钮，点击并结束循环1并启动循环3；若是 每天10:00开始抢购 则返回前一页
function loop2() {
    console.log('进入预约抢购页面');
    while (true) {
        var do3_press = className("android.widget.Button").text('预约抢购').findOnce();
        if (do3_press) {
            console.log('点击【预约抢购】');
            do3_press.click();
            threads.start(function () {
                loop3();
            });
            break;
        }

        var do2_back = className("android.widget.Button").text('每天10:00开始抢购').findOnce();
        if (do2_back) {
            console.log('预约还未开始【返回】');
            back();
            threads.start(function () {
                loop1();
            });
            break;
        }
    }
}


// 循环3查找20秒后的提交订单按钮 （根据弹窗情况决定是重复提交还是结束抢购）
function loop3() {
    console.log('进入确认下单页面');
    while (true) {
        var sub_order = className("android.widget.Button").text('确认下单').findOnce();
        if (sub_order) {
            // 设置购买数量（根据设置的数量和坐标直接点击几次）
            add_count();
            sub_order.click();
            console.log('点击【确认下单】');
        }

        var ok_btn = className("android.widget.Button").text('确认').findOnce();
        if (ok_btn) {
            ok_btn.click();
        }

        // loop2中没抢到的时候的
        var over_btn = className("android.widget.Button").text('好的').findOnce();
        if (over_btn) {
            over_btn.click();
            exit();
        }

        sleep(200);
    }
}

// 增加购买数量
function add_count() {
    let buy_count = storage.get("itemNum", 1);
    let buy_xAxis = storage.get("xAxis", 969);
    let buy_yAxis = storage.get("yAxis", 1344);
    if (buy_count > 1) {
        for (let i = 1; i < buy_count; i++) {
            // console.log('press', buy_xAxis, buy_yAxis);
            // press(buy_xAxis, buy_yAxis, 10);
            generalClick(buy_xAxis, buy_yAxis);
        }
    }
}

// 物美多点时间戳和当前时间戳的差
function getDuoDianTime() {
    var cur = new Date().getTime();
    let start = new Date().getTime()
    var response_duodian = http.get("https://appapis.dmall.com/static/queryUserCheckInfo.jsonp");
    var duodian_Time = response_duodian.body.string();
    let end = new Date().getTime()
    var json = eval(duodian_Time)
    var duodian_Time = json.result.data.currentTime;
    var duodian_number_time = Number(duodian_Time);
    let diff = end - start
    console.log('服务器请求时间：' + diff + "MS"); // 该方法精准度不高，只能在ms内
    console.log("多点时间：", formatDate(new Date(duodian_number_time)));
    return duodian_number_time - cur - (diff * 2 / 3);
}

// 获取下一个可抢购的10点的时间戳
function getNextSeckillTime() {
    var now = new Date();
    var curr_year = now.getFullYear();
    var curr_month = now.getMonth() + 1;
    var curr_date = now.getDate();

    var seckill_time_str = curr_year + '/' + curr_month + '/' + curr_date + ' 10:00:00';
    seckill_date = new Date(seckill_time_str);

    // 当前时间大于目标时间，那么目标时间往后延一天
    if (now.getTime() > seckill_date.getTime()) {
        seckill_date = new Date(seckill_date.getTime() + 24 * 60 * 60 * 1000);
    }

    return seckill_date.getTime();
}

//将num左补0为len长度的字符串
function lpadNum(num, len) {
    var l = num.toString().length;
    while (l < len) {
        num = "0" + num;
        l++;
    }
    return num;
}
//将传入的Date格式化为"yyyyMMdd HH:mm:ss.SSS"
function formatDate(d) {
    var year = d.getFullYear();
    var month = d.getMonth() + 1;
    var day = d.getDate();
    var hours = d.getHours();
    var minutes = d.getMinutes();
    var seconds = d.getSeconds();
    var milliSeconds = d.getMilliseconds();
    var resStr = year + lpadNum(month, 2) + lpadNum(day, 2) + " " + lpadNum(hours, 2) + ":" + lpadNum(minutes, 2) + ":" + lpadNum(seconds, 2) + "." + lpadNum(milliSeconds, 3);
    return resStr;
}

// 通用点击事件（不同分辨率会进行坐标转换）
function generalClick(x, y) {
    // 注意：测试机型为1080*2340，你可以根据自己的机型修改
    x1 = device.width / 1080
    y1 = device.height / 2340
    press(x * x1, y * y1, 10);
}
